<?php

namespace app\api\controller;

use app\common\controller\Api;
use Endroid\QrCode\Builder\Builder;
use Endroid\QrCode\Builder\BuilderInterface;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelHigh;
use Endroid\QrCode\Label\Alignment\LabelAlignmentCenter;
use Endroid\QrCode\Label\Font\NotoSans;
use Endroid\QrCode\QrCode;
use fast\Express100;
use GuzzleHttp\Cookie\CookieJar;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Config;
use think\Db;
use Endroid\QrCode\Color\Color;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelLow;
use Endroid\QrCode\Label\Label;
use Endroid\QrCode\Logo\Logo;
use Endroid\QrCode\RoundBlockSizeMode\RoundBlockSizeModeMargin;
use Endroid\QrCode\Writer\PngWriter;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];


    //二维码测试
    public function qrcode(){
        $writer = new PngWriter();
        $url = "http://www.baidu.com";
// Create QR code
        $qrCode = QrCode::create($url)
            ->setEncoding(new Encoding('UTF-8'))
            ->setErrorCorrectionLevel(new ErrorCorrectionLevelLow())
            ->setSize(300)
            ->setMargin(10)
            ->setRoundBlockSizeMode(new RoundBlockSizeModeMargin())
            ->setForegroundColor(new Color(0, 0, 0))
            ->setBackgroundColor(new Color(255, 255, 255));

// Create generic logo
//        $logo = Logo::create(__DIR__.'/assets/symfony.png')
//            ->setResizeToWidth(50);

// Create generic label
        $label = Label::create('Label')
            ->setTextColor(new Color(255, 0, 0));

        $result = $writer->write($qrCode,null, $label);

// Directly output the QR code
        header('Content-Type: '.$result->getMimeType());
        echo $result->getString(); die;
// Save it to a file
        $result->saveToFile(__DIR__.'/qrcode.png');    //保存图片

// Generate a data URI to include image data inline (i.e. inside an <img> tag)
        $dataUri = $result->getDataUri();  //返还base64图片字符串
    }

    //二维码测试1
    public function qrcode1(){
        $color = new Color(0,0,255);
        $color1 = new Color(0,255,0);
        $color2 = new Color(255,182,193);
        $color3 = new Color(250,0,0);
        $mar = new Margin(30,10,10,10);

        $url = "http://www.baidu.com";
        $result = Builder::create()
            ->writer(new PngWriter())
            ->writerOptions([])
            ->data($url)   //文本或url地址
            ->errorCorrectionLevel(new ErrorCorrectionLevelHigh())
            ->size(500)     //二维码大小
            ->margin(10)    //外边距
            ->foregroundColor($color)    //二维码颜色
            ->backgroundColor($color1)    //背景颜色
            ->logoResizeToWidth('80')    //logo宽
            ->logoResizeToHeight('80')    //logo高
            ->roundBlockSizeMode(new RoundBlockSizeModeMargin())
            ->logoPath(__DIR__.'/assets/symfony.png')     //logo图片位置
            ->labelText('二维码')     //标题文字
            ->labelMargin($mar)     //标题文字的外边距
            ->labelTextColor($color3)     //标题文字颜色
            ->labelFont(new NotoSans(20))
            ->labelAlignment(new LabelAlignmentCenter())
            ->build();

        // 设置页面文本类型
        header('content-type:'.$result->getMimeType());
        echo $result->getString();     //图片内容
        die;
        // 二维码保存位置
        $result->saveToFile('qrcode.png');
        // 生成图像数据url
        $dataUri = $result->getDataUri();  //base64图片字符串
    }


    public function test(){
        $name = 'newbie_guide';
        $value = Config::get('site.'.$name);

        p(cdnurl('',true));
      //  $value = pregReplaceImg($value,cdnurl('',true));
        $prefix = cdnurl('',true);
        $value = <<<of
adlfsdfjlsdkfjsdlf<img src="http://www.baidu.com/uploads/aa.png"  width="1000" /> 1222s888
adsfsdf<img style= " color: red " src="/uploads/bb.png"  width="100">1111122 
of;



      $html = preg_replace_callback('/(<[img|IMG].*?src=)([\'\"])(.*?)\\2(.*?>)/ui', function ($match) use ($prefix) {
                p($match);
            if (strpos($match[3], 'http://') === false && strpos($match[3], 'https://') === false){
                return  $match[1].$match[2].$prefix ."/".trim($match[3],"/").$match[2].$match[4];
            }else{
                return $match[0];
            }
        }, $value);
      p($html);die;
        $html1 = preg_replace_callback('/(<[img|IMG].*?style=\s*?([\'\"]))(.*?)\\2/ui', function ($match) {
           // p($match);die;
            return $match[1] . 'width:100%' . $match[2];
        }, $html);

      p($html);
      echo "<br />";
        echo "<br />";
        p($html1);die;
        p($value);die;
    }


    public function download(){
        $file = $this->request->get('url');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, "w");
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding != 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }


        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);


            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                $row = [];
                $temp = array_combine($fields, $values);
                foreach ($temp as $k => $v) {
                    if (isset($fieldArr[$k]) && $k !== '') {
                        $row[$fieldArr[$k]] = $v;
                    }
                }
                if ($row) {
                    $insert[] = $row;
                }
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }
    }

    public function article(){
        $list = Db::name('news')->where('switch',1)->field([
            'id','title','createtime'
        ])->order('id desc')->paginate(20)->each(function($item,$key){
            $item['createtime'] = date("Y-m-d",$item['createtime']);
            return $item;
        });
        $this->success('',$list);
    }

    public function articleinfo(){
        $id = $this->request->param('id');
        $info= Db::name('news')->where('id',$id)->field(
            'id,title,content,createtime'
        )->find();
        $info['createtime'] = date("Y-m-d",$info['createtime']);
        $this->success('',$info);
    }

    public function express(){
        $no = $this->request->param('no');
        $ar = Express100::getExpressInfo($no);
        p($ar);die;
    }


}
